package com.qf.hotel.controller.menu;

import com.alibaba.fastjson.JSON;
import com.qf.hotel.pojo.Menu;
import com.qf.hotel.pojo.ResultVO;
import com.qf.hotel.service.MenuService;
import com.qf.hotel.service.impl.MenuServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author: GsheN丶
 * @date: 2021/6/23 15:01
 * @description:
 */
@WebServlet("/menu/list")
public class MenuController extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //字符编码设置
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //把得到的结果存入resultVO,把resultVO响应出去
        ResultVO resultVO = new ResultVO();

        try {
            //创建业务对象查询数据
            MenuService menuService = new MenuServiceImpl();
            List<Menu> menus = menuService.findAll();

            //数据设置到域中
            request.getSession().setAttribute("menus",menus);

            //如果使用ajax加载,需要响应给前端
            //response.getWriter().write(menus);


            //响应给前端
//            String jsonString = JSON.toJSONString(menus);
//            System.out.println("jsonString = " + jsonString);

            resultVO.setMessage("请求成功");
            resultVO.setSuccess(true);
            resultVO.setData(menus);

            response.getWriter().write(JSON.toJSONString(resultVO));


        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
